//
//  DoubleExt.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 06.04.25.
//

import Foundation
extension Double {
    // 去除末尾的0
    func toStringWithoutTrailingZeros() -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = 0
        formatter.maximumFractionDigits = 2
        formatter.numberStyle = .decimal
        formatter.groupingSeparator = ""      // 设置为空字符串
        formatter.usesGroupingSeparator = false // 禁用分组
        formatter.decimalSeparator = "."
        return formatter.string(from: NSNumber(value: self)) ?? String(self)
    }
    
    func toAmountWithSign() -> String {
        return "¥\(String(describing: self.toStringWithoutTrailingZeros()))"
    }
    
    func toAmountTwoDecimalPlaces() -> String {
        return String(format: "%.2f", self)
    }
    
    func toPercent() -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = 0
        formatter.maximumFractionDigits = 1
        formatter.roundingMode = .halfUp
        formatter.numberStyle = .percent
        formatter.groupingSeparator = ""      // 设置为空字符串
        formatter.usesGroupingSeparator = false // 禁用分组
        formatter.decimalSeparator = "."
        return formatter.string(from: NSNumber(value: self)) ?? "%0"
    }
}
